package cn.com.sparkle.paxos.stablestorage;

import java.io.File;
import java.io.IOException;

/**
 * 
 * This is the version of local file. This will be the foundation of file upgrade in future.
 * @author qinan.qn
 *
 */
public class StoreVersion {
	public final static String VERSION = "0.0.1";

	public static String readCurVersion(File f) throws IOException {
		File[] files = f.listFiles();
		File tmpVersion = null;
		File version = null;
		for (File file : files) {
			if (!file.isDirectory()) {
				String[] name = file.getName().split("-");
				if (name.length == 2) {
					//restore from tmp
					if (name[0].equals("tmpversion")) {
						tmpVersion = file;
					} else if (name[0].equals("version")) {
						version = file;
					}
				}
			}
		}
		if (tmpVersion != null) {
			//the tmp version is latest, restore from tmp version
			if (version != null) {
				version.delete();
			}
			String[] name = tmpVersion.getName().split("-");
			File newFile = new File(f.getCanonicalPath() + "/version-" + name[1]);
			tmpVersion.renameTo(newFile);
			return name[1];
		} else if (version != null) {
			String[] name = version.getName().split("-");
			return name[1];
		} else {
			File newFile = new File(f.getCanonicalPath() + "/version-" + VERSION);
			newFile.createNewFile();
			return VERSION;
		}
	}
}
